package com.jiyun.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.config.TencentCloudProperties;
import com.jiyun.login.dto.UpdatePasswordDto;
import com.jiyun.login.dto.UserInfoDto;
import com.jiyun.login.pojo.User;
import com.jiyun.login.vo.CosUploadVo;
import com.jiyun.login.vo.UserInfoVo;
import com.jiyun.mapper.UsersMapper;
import com.jiyun.result.ResultCodeEnum;
import com.jiyun.service.UsersService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
* @author zqtao
* @description 针对表【users】的数据库操作Service实现
* @createDate 2025-02-12 10:00:19
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User>
    implements UsersService {

    @Override
    public String login(User user) {

        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return "用户名或密码不能为空";
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        wrapper.eq(User::getPassword, user.getPassword());

        User one = getOne(wrapper);

        if (one == null){
            return "用户名或密码错误";
        }

        StpUtil.login(one.getUserId());

        return "登录成功";

    }

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public User getInfo(Long loginId) {
        return usersMapper.getInfo(loginId);
    }

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        //连接腾讯云
        COSClient cosClient = getPrivateCosClient();
        //设置上传元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentType(file.getContentType());
        meta.setContentEncoding("UTF-8");
        //向桶中保存信息
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String uploadPath = "/avatar/"+path+"/"+ UUID.randomUUID().toString().replace("-", "")+fileType;
        //获取腾讯云的存储位置
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(),uploadPath,file.getInputStream(),meta);
            putObjectRequest.setStorageClass(StorageClass.Standard);
            //上传
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            cosClient.shutdown();
            CosUploadVo cosUploadVo = new CosUploadVo();
            cosUploadVo.setUrl(uploadPath);
            //回显路径
            cosUploadVo.setShowUrl(this.getImageUrl(uploadPath));
            return cosUploadVo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private COSClient getPrivateCosClient() {
        //初始化用户身份信息
        COSCredentials cred = new BasicCOSCredentials(tencentCloudProperties.getSecretId(),tencentCloudProperties.getSecretKey());
        //设置 bucket 的地域
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        //生成 cos 客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    @Override
    public String getImageUrl(String path) {
        if(!StringUtils.hasText(path)){
            return "";
        }
        COSClient cosClient = getPrivateCosClient();
        //自动生成签名
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path, HttpMethodName.GET);
        // 设置签名过期时间(可选), 若未进行设置则默认使用 ClientConfig 中的签名过期时间(1小时)
        // 这里设置签名在半个小时后过期
        Date expirationDate = new DateTime().plusMinutes(3600).toDate();
        request.setExpiration(expirationDate);
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }

    @Override
    public String updateInfo(UserInfoDto userInfoDto, Long loginId) {
        User user = usersMapper.selectById(loginId);
        user.setAvatar(userInfoDto.getAvatar());
        user.setPhone(userInfoDto.getPhone());
        user.setRemark(userInfoDto.getRemark());
        user.setStatus(userInfoDto.getStatus());
        usersMapper.updateById(user);
        return "保存成功";
    }

    @Override
    public UserInfoVo findNickAvatar(Long loginId) {
        User user = usersMapper.selectById(loginId);
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setNickName(user.getNickname());
        userInfoVo.setAvatar(user.getAvatar());
        return userInfoVo;
    }

    @Override
    public String updatePassword(UpdatePasswordDto updatePasswordDto, Long loginId) {
        User user = usersMapper.selectById(loginId);
        if(user.getPassword().equals(updatePasswordDto.getOldPassword())){
            user.setPassword(updatePasswordDto.getNewPassword());
            usersMapper.updateById(user);
            return "修改成功";
        }
        return "旧密码输入错误，请重新输入";
    }


}




